<script lang="ts" setup>
import { computed, defineEmits, defineProps, ref, unref, useAttrs } from 'vue';
import type { FormInst } from 'naive-ui';
import FormItem from '@/components/form/modules/form-item.vue';
import type { FormElementType, FormProps } from './props';

// 使用 defineProps 宏来定义 props
// const props = defineProps<{
//   size: FormProps['size'];
// }>();
// 使用 withDefaults 设置默认值
const elementType: FormElementType[] = ['number', 'select', 'checkbox', 'radio', 'date', 'time'];
const props = withDefaults(defineProps<FormProps>(), {
  size: 'medium',
  labelWidth: 80,
  labelPosition: 'left',
  inline: true,
  showSubmit: true
});
const attrs = useAttrs();
// 提取除 formItems、modelValue、rules 外的其他属性（用于 NForm 绑定）
const { formItems, rules, formGrid, showSubmit, ...nFormProps } = props;
// 定义 emits（如果需要）
const emit = defineEmits<{
  (e: 'submit', value: any): void;
  (e: 'reset'): void;
}>();

const val = computed(() => {
  const arr = formItems || [];
  const arrVal = arr.map(item => {
    if (item.component === 'input' || item.component === 'textarea') {
      return { [item.path]: '' };
    } else if (elementType.includes(item.component)) {
      return { [item.path]: null };
    }
    return { [item.path]: null };
  });

  return Object.assign({}, ...arrVal);
});

const formRef = ref<FormInst | null>(null);
const formValue = ref({ ...unref(val) });

// 重置
function handleResetClick() {
  Object.keys(formValue.value).forEach(key => {
    formValue.value[key] = '';
  });
  formRef.value?.restoreValidation();
  emit('reset');
}

function handleValidateClick(e: MouseEvent) {
  e.preventDefault();
  formRef.value?.validate(errors => {
    if (!errors) {
      emit('submit', formValue.value); // 触发事件通知父组件
    }
  });
}
function getFormValue() {
  return formValue.value;
}

function setFormValue(params: any) {
  formValue.value = params;
}

function validate(e: MouseEvent, cb: (valid: boolean) => void) {
  e.preventDefault();
  formRef.value?.validate(errors => {
    if (!errors) {
      cb(true);
    } else {
      cb(false);
    }
  });
}

defineExpose({
  getFormValue,
  setFormValue,
  validate
});
</script>

<template>
  <NForm ref="formRef" v-bind="nFormProps" :model="formValue" :rules="rules">
    <NGrid x-gap="12">
      <NGi v-for="item in formItems" :key="item.path" :span="item.grid?.span">
        <FormItem
          v-model="formValue[item.path]"
          :path="item.path"
          :label="item.label"
          :type="item.component"
          :attrs="item.componentProps"
          :rules="item.rules"
        />
      </NGi>
      <NGi v-if="showSubmit" :span="formGrid?.span" class="o-form-item">
        <NFormItem>
          <NSpace>
            <NButton @click="handleResetClick">
              <template #icon>
                <icon-material-symbols:reset-settings-outline-rounded class="text-icon" />
              </template>
              重置
            </NButton>
            <NButton type="primary" :loading="attrs.loading as boolean" ghost @click="handleValidateClick">
              <template #icon>
                <icon-gravity-ui:magnifier class="text-icon" />
              </template>
              搜索
            </NButton>
          </NSpace>
        </NFormItem>
      </NGi>
    </NGrid>
  </NForm>
</template>

<style lang="scss" scoped>
.o-form-item {
  display: flex;
  justify-content: flex-end;
}
</style>
